<?php
/**
 * 系统每日流水
 */
namespace App\Models\MainDB\Statistics;

use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;

class SystemEverydaySerial extends Model
{
    protected $table = 'ln_system_everyday_serial';

    protected $primaryKey = 'id';

    protected $fillable = [
        'id', //主键ID
        'date', //日期
        'room_gift_serial', //房间礼物流水
        'blind_box_serial', //盲盒流水
        'lucky_tree_serial', //许愿树流水
        'scramble_sugar_serial', //抢糖游戏流水
        'huoke_serial', //霍克城堡流水
        'ad_astra_serial', // 星际探险流水
        'star_wishing_serial', // 欢乐大作战流水
    ];

    public $timestamps = false;

    //按日期统计
    public function getSum($fields, $date)
    {
        $formatFields = $fieldTotal = '';
        foreach ($fields as $field) {
            $formatFields .= "sum($field) as $field,";
            $fieldTotal .= "sum($field)+";
        }
        $formatFields = rtrim($formatFields, ',');
        $fieldTotal = rtrim($fieldTotal, '+') . ' as total';

        $data = $this
            ->select(DB::raw($formatFields), DB::raw($fieldTotal))
            ->where(function ($query) use ($date) {
                if (is_array($date)) {
                    $query->whereBetween('date', $date);
                } else {
                    $query->where('date', $date);
                }
            })
            ->first();
        if ($data) {
            $data = $data->toArray();
            $data = array_map(function ($elem) {
                if (is_null($elem)) {
                    return 0;
                } else {
                    return $elem;
                }
            }, $data);
            return $data;
        }
        $data = ['total' => 0];
        foreach ($fields as $field) {
            $data[$field] = 0;
        }
        return $data;
    }

    //获取最新更新时间
    public function getLatestUpdateTime($date = null)
    {
        return $this->where(function ($query) use ($date) {
            if ($date) {
                $query->where('date', $date);
            }
        })->max('updated_at');
    }
}
